package com.wn.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @FileName: MyHttpChannelHandler
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/7/29 - 17:01
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class MyHttpChannelHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            URI uri = new URI(request.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("被过滤的请求: " + uri.getPath());
                return;
            }

            System.out.println("消息类型: " + msg.getClass());
            System.out.println("客户端地址:" + ctx.channel().remoteAddress());
            System.out.println("请求METHOD: " + request.method());
            System.out.println("请求URI: " + uri.getPath());
            System.out.println("请求PORT: " + uri.getPort());
            System.out.println("请求getAuthority: " + uri.getAuthority());
            System.out.println("请求getUserInfo: " + uri.getUserInfo());
            System.out.println("请求getFragment: " + uri.getFragment());

            ByteBuf content = Unpooled.copiedBuffer("success", CharsetUtil.UTF_8);
            // 创建应答体
            HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            // 设置返回头
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            // 返回消息
            ctx.writeAndFlush(response);
        }
    }
}
